﻿(function ($) {

    function ShowFoundData(rows) {
        var i, k;
        var car_id, vend_name, model_name, color_name, engine, price;
        var cells = $('#RightPanelContent td');

        for (i = 0; i < rows.length; i++) {
            car_id = rows[i].cell[0];
            vend_name = rows[i].cell[2];
            model_name = rows[i].cell[4];
            color_name = rows[i].cell[6];
            engine = rows[i].cell[7];
            price = rows[i].cell[8];
            comment = rows[i].cell[9];

            cells.eq(i).html(vend_name + '<br/>' + model_name +
            '<br/>' + color_name + '<br/>' + engine + 'л.<br/><span car_id="' + car_id + '">' + price + '</span><br/>' + comment);
            cells.eq(i).css({ 'border-left-color': '#E0E0E0', 'border-top-color': '#E0E0E0' });
        }
        for (k = i; k < app.viewgrid.rows * app.viewgrid.cols; k++) {
            cells.eq(k)
                .html('')
                .css({ 'border-left-color': 'transparent', 'border-top-color': 'transparent' });
        }

        var price_val = $('#RightPanelContent span[car_id]');
        price_val.css({ 'text-decoration': 'underline', 'cursor': 'pointer' });
        for (i = 0; i < price_val.length; i++) {
            $(price_val[i]).click({ vdiv: 'CarPrice', car_id: $(price_val[i]).attr('car_id') }, function (ev) {
                app.ShowPriceHistory(ev.data.vdiv, ev.data.car_id);
            });
        }

    }


    function DoSearch(pgID, pgNum) {
        var reqData = {
            source: 'CarCatalogue',
            oper: 'find',
            page: pgNum,
            rows: app.viewgrid.rows * app.viewgrid.cols,
            sidx: app.viewgrid.sort,
            sord: 'ASC',
            _search: true
        }
        var vend = app.form.vend.val();
        var model = app.form.model.val();
        var color = app.form.color.val();
        var engine = app.form.engine.val();
        var lprice = app.form.lprice.val();
        var hprice = app.form.hprice.val();
        var s_date = app.form.s_date.val();

        if (vend != '') reqData.vend_name = vend;
        if (model != '') reqData.model_name = model;
        if (color != '') reqData.color_name = color;
        if (engine != '') reqData.engine = engine;
        if (lprice != '') reqData.lprice = lprice;
        if (hprice != '') reqData.hprice = hprice;
        if (s_date != '') reqData.s_date = s_date;

        $.post('cars_cb.aspx', reqData,
                function (rsp, textStatus) {
                    if (!rsp || !rsp.total) {
                        app.alert('AlertDlg', 'Внимание', 'Записей, соответствующих заданным условиям, не найдено', 'ipdepo-icon-info32');
                        return;
                    }
                    PaginatorCB('Paginator', rsp.page, rsp.total);
                    ShowFoundData(rsp.rows);
                }, 'json');
    }


    //        app.viewgrid = { rows: str, cols: col, sort: sort };
    function PaginatorCB(pgID, pgNum, pgTot) {
        var pgn = $('#' + pgID);
        var newpg = (pgn.length == 0) ? false : true;

        while (true) {
            if (pgTot < 2) { pgn.hide(); break; }

            pgn.show();

            if (newpg) {
                pgn.html(
                '<div style="width:64px; float:left">Страницы:&nbsp;</div>' +
                '<a id="' + pgID + '_m_left"></a><div id="' + pgID + '_o_left"></div>' +
                '<div class="paginator_p_wrap"><div class="paginator_p_bloc"></div></div>' +
                '<div id="' + pgID + '_o_right"></div><a id="' + pgID + '_m_right"></a>' +
                '<div class="paginator_slider" style="left:96px;"' +
                'class="ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all">' +
                '<a class="ui-slider-handle ui-state-default ui-corner-all" href="#"></a></div>'
                );

                $('#' + pgID + '_m_left').addClass("ui-icon ui-icon-seek-first").css({ 'float': 'left', 'cursor': 'pointer' });
                $('#' + pgID + '_o_left').addClass("ui-icon ui-icon-seek-prev").css({ 'float': 'left', 'cursor': 'pointer' });
                $('#' + pgID + '_o_right').addClass("ui-icon ui-icon-seek-next").css({ 'float': 'left', 'cursor': 'pointer' });
                $('#' + pgID + '_m_right').addClass("ui-icon ui-icon-seek-end").css({ 'float': 'left', 'cursor': 'pointer' });

                pgn.jPaginator({
                    selectedPage: pgNum,
                    nbPages: pgTot,
                    nbVisible: 5,
                    overBtnLeft: '#' + pgID + '_o_left',
                    overBtnRight: '#' + pgID + '_o_right',
                    maxBtnLeft: '#' + pgID + '_m_left',
                    maxBtnRight: '#' + pgID + '_m_right',
                    onPageClicked: function (a, num) {
                        DoSearch('Paginator', num);
                    }
                });
            }
            else
                pgn.trigger("reset", { nbPages: pgTot, selectedPage: pgNum });

            pgn.css({ 'top': (pgn.parent().innerHeight() - pgn.outerHeight()) / 2 });
            break;
        }
    }

    app.SearchForm = function (formId, treeId) {
        $('#' + formId).html(' \
        <table> \
            <tr><td><label>Марка:</label><input name="vendor" type="text" value=""/></td> \
            <td><label>Модель:</label><input name="model" type="text" value=""/></td></tr> \
            <tr><td><label>Цвет:</label><input name="color" type="text" value=""/></td> \
            <td><label>Объем:</label><input name="engine" type="text" value=""/></td></tr> \
            <tr><td><label>Цена от:</label><input name="lprice" type="text" value=""/></td> \
            <td><label>до:</label><input name="hprice" type="text" value=""/></td></tr> \
            <tr><td><label>Состоянием на:</label><input name="date" type="text" value=""/></td> \
            <td style="vertical-align: bottom;"><button type="button" name="find">Искать</button></td></tr>\
        </table> \
        ');

        var form = {
            vend: $('#' + formId + ' input[name="vendor"]'),
            vend_id: 0,
            model: $('#' + formId + ' input[name="model"]'),
            model_id: 0,
            color: $('#' + formId + ' input[name="color"]'),
            color_id: 0,
            engine: $('#' + formId + ' input[name="engine"]'),
            lprice: $('#' + formId + ' input[name="lprice"]'),
            hprice: $('#' + formId + ' input[name="hprice"]'),
            s_date: $('#' + formId + ' input[name="date"]'),
            sb: $('#' + formId + ' button[name="find"]')
        };

        form.sb.button({ icons: { primary: 'ui-icon-search'} });
        form.sb.bind('click', function () {
            //            PaginatorCB('Paginator', 1, 12);
            $('#Paginator').hide();
            DoSearch('Paginator', 1);
        });

        form.vend.autocomplete({
            source: function (request, responce) {
                $.post('callbacks.aspx', { source: 'VendorDictionary', oper: 'find', term: request.term },
                function (rsp, textStatus) {
                    if (rsp.errcode) {
                        if (rsp.errcode == '999') { alert(rsp.errmess); location.href = 'Default.aspx'; }
                        else app.alert('AlertDlg', 'Ошибка', rsp.errmess, 'ipdepo-icon-stop32');
                        responce();
                        return;
                    }
                    if (rsp.data) {
                        responce($.map(rsp.data, function (item) {
                            return { label: item.name, value: item.value }
                        }));
                        return;
                    }
                    responce();
                }, 'json');
            },
            minLength: 2, autoFocus: true,
            focus: function (event, ui) { form.vend.val(ui.item.label); return false; },
            select: function (event, ui) {
                form.vend.val(ui.item.label);
                form.vend_id = ui.item.value;
                form.model.val("");
                form.model_id = 0;
                return false;
            }
        });

        form.model.autocomplete({
            source: function (request, responce) {
                $.post('callbacks.aspx', { source: 'ModelDictionary', oper: 'find', term: request.term, vend_id: form.vend_id },
            function (rsp, textStatus) {
                if (rsp.errcode) {
                    if (rsp.errcode == '999') { alert(rsp.errmess); location.href = 'Default.aspx'; }
                    else app.alert('AlertDlg', 'Ошибка', rsp.errmess, 'ipdepo-icon-stop32');
                    responce();
                    return;
                }
                if (rsp.data) {
                    responce($.map(rsp.data, function (item) {
                        return { label: item.name, value: item.value }
                    }));
                    return;
                }
                responce();
            }, 'json');
            },
            minLength: 2, autoFocus: true,
            focus: function (event, ui) { form.model.val(ui.item.label); return false; },
            select: function (event, ui) {
                form.model.val(ui.item.label);
                form.model_id = ui.item.value;
                return false;
            }
        });

        form.color.autocomplete({
            source: function (request, responce) {
                $.post('callbacks.aspx', { source: 'ColorDictionary', oper: 'find', term: request.term },
                function (rsp, textStatus) {
                    if (rsp.errcode) {
                        if (rsp.errcode == '999') { alert(rsp.errmess); location.href = 'Default.aspx'; }
                        else app.alert('AlertDlg', 'Ошибка', rsp.errmess, 'ipdepo-icon-stop32');
                        responce();
                        return;
                    }
                    if (rsp.data) {
                        responce($.map(rsp.data, function (item) {
                            return { label: item.name, value: item.value }
                        }));
                        return;
                    }
                    responce();
                }, 'json');
            },
            minLength: 2, autoFocus: true,
            focus: function (event, ui) { form.color.val(ui.item.label); return false; },
            select: function (event, ui) {
                form.color.val(ui.item.label);
                form.color_id = ui.item.value;
                return false;
            }
        });

        form.s_date.datepicker({
            dateFormat: "dd.mm.yy",
            changeMonth: true,
            changeYear: true
        });

        $('#' + treeId).dynatree(
        {
            autoFocus: false,
            autoCollapse: true,
            initAjax: {
                url: "form_cb.aspx",
                data: { node_id: "0", source: "CarTree" }
            },
            onLazyRead: function (node) {
                node.appendAjax({
                    url: "form_cb.aspx",
                    data: { node_id: node.data.key, source: "CarTree" }
                });
            },
            onActivate: function (node) {
                var subkeys = node.data.key.split('.');
                if (subkeys.length == 2) {
                    form.vend_id = subkeys[0];
                    $('#' + formId + ' input[name="vendor"]').val(this.getNodeByKey(subkeys[0]).data.title);
                    form.model_id = subkeys[1];
                    $('#' + formId + ' input[name="model"]').val(node.data.title);
                }
                else {
                    form.vend_id = subkeys[0];
                    $('#' + formId + ' input[name="vendor"]').val(node.data.title);
                    form.model_id = 0;
                    $('#' + formId + ' input[name="model"]').val("");
                }
            }
        });

        //       $('#LeftPanelContent').append('<button id="TreeReload" type="button" name="treereload">Ok</button>');
        $('button#TreeReload')
        //            .css({ 'position': 'absolute', 'left': '150px', 'top': '208px', 'width':'32px', 'height':'24px' })
            .button({ text: false, icons: { primary: 'ui-icon-refresh'} });

        $('button#TreeReload').bind('click', function () {
            var tree = $('#' + treeId).dynatree("getTree");
            tree.reload();
        });

        app.form = form;
    }


    app.EditMenu = function (dombut) {
        var menubut = $('#' + dombut);
        var menulist = dombut + '_items';

        function killmenu() {
            $('#' + dombut).unbind('focusout', killmenu);
            $('#' + menulist).menu('destroy');
            $('#' + menulist).remove();
        };

        menubut.button({ icons: { primary: "ui-icon-pencil", secondary: "ui-icon-triangle-1-s"} });
        menubut.bind('click',
			function () {
			    var exists = $('#' + menulist).length ? true : false;
			    if (exists) killmenu();
			    else {
			        $('<ul id="' + menulist + '" style="position: absolute; top: -1000px; z-index:1500;"></ul>').appendTo(document.body);
			        $('#' + menulist).html(
						'<li oper="Catalogue"><a href="#" oper="Catalogue">Каталог автомобилей</a></li> \
						 <li oper="Models"><a href="#" >Справочник моделей</a></li> \
						 <li oper="Vendors"><a href="#">Справочник марок</a></li> \
						 <li oper="Colors"><a href="#">Справочник цветов</a></li>'
					);

			        $('#' + menulist).menu({
			            selected: function (event, ui) {
			                var oper = ui.item.attr('oper');
			                killmenu();

			                // alert(ui.item.attr('oper'));
			                switch (oper) {
			                    case 'Colors':
			                        app.ShowColorDictionary('ColorDic');
			                        break;
			                    case 'Catalogue':
			                        app.ShowCarCatalogue('CarCatalogue');
			                        break;
			                    case 'Models':
			                        app.ShowModelDictionary('ModelDic');
			                        break;
			                    case 'Vendors':
			                        app.ShowVendorDictionary('VendorDic');
			                        break;
			                }
			            }
			        });

			        $('#' + menulist).position({ my: 'left top', at: 'left bottom', of: menubut });
			        $('#' + menulist).mouseover(function () { $('#' + dombut).unbind('focusout', killmenu); });
			        $('#' + menulist).mouseleave(function () { $('#' + dombut).bind('focusout', killmenu); });

			        $('#' + dombut).focusout(killmenu);

			    }
			}
		);
    }

    app.SetViewGrid = function (str, col, sort) {
        var n, i;
        var cells, cols;

        if (!str) str = 4;
        if (!col) col = 5;

        cells = '';
        for (n = 0; n < str; n++) {
            cols = '';
            for (i = 0; i < col; i++) cols = cols + '<td></td>';
            cells = cells + '<tr>' + cols + '</tr>';
        }
        $('.right_panel_content table').html(cells);
        $('.right_panel_content table').css({ 'width': col * 185 + 30 });
        app.viewgrid = { rows: str, cols: col, sort: sort };
        $('#Paginator').hide();
    };

    app.ViewOptions = function (dombut, dlgID) {
        var optbut = $('#' + dombut);

        optbut.button({ icons: { primary: "ui-icon-gear"} });
        optbut.bind('click',
		function () {
		    var aldlg = $('#' + dlgID);

		    aldlg.html(
                    '<p>Количество строк: <span id="strnum"></span></p>' +
                    '<div id="rowslider"></div></br>' +
                    '<p>Количество столбцов: <span id="colnum"></span></p>' +
                    '<div id="colslider"></div></br>' +
                    '<p>Сортировать по: <select id="viewgridsort">' +
                        '<option value="vend_name" >Марка автомобиля</option>' +
                        '<option value="model_name">Модель автомобиля</option>' +
                        '<option value="color_name">Цвет автомобиля</option>' +
                        '<option value="engine"  >Обьем двигателя</option>' +
                        '<option value="price"   >Цена автомобиля</option>' +
                    '</select></p>'
            );

		    $('#viewgridsort option[value="' + app.viewgrid.sort + '"]').attr('selected', 'selected');

		    $("#rowslider").slider({ value: app.viewgrid.rows, min: 1, max: 10, step: 1,
		        slide: function (event, ui) { $("#strnum").text(ui.value); }
		    });
		    $("#strnum").text($("#rowslider").slider("value"));

		    $("#colslider").slider({ value: app.viewgrid.cols, min: 1, max: 10, step: 1,
		        slide: function (event, ui) { $("#colnum").text(ui.value); }
		    });
		    $("#colnum").text($("#colslider").slider("value"));

		    aldlg.dialog(
            {
                modal: true, title: "Опции просмотра",
                height: 'auto', width: 'auto',
                zIndex: app.ui_dialog_min_z_index,
                autoOpen: false, resizable: false,
                open: function () { $('div[aria-labelledby="ui-dialog-title-' + dlgID + '"]').shadow() },
                close: function () {
                    $(this).dialog("destroy");
                    $.ui.dialog.maxZ = $.maxZIndex({ group: '.ui-dialog.ui-widget' });
                },
                buttons: {
                    "Применить": function () {
                        var newsort = $('#viewgridsort').val();
                        app.SetViewGrid(
                            $("#rowslider").slider("value"),
                            $("#colslider").slider("value"),
                            $('#viewgridsort').val()
                        );
                        $(this).dialog("close");
                    },
                    "Отмена": function () {
                        $(this).dialog("close");
                        $('#' + dlgID + ' *').remove(); 
                    }
                }
            });

		    aldlg.dialog('open');
		});
    };


    // ---------------------------------------------------------------------------
})(jQuery);
